/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.impl.service.internal.chargedpresc.command;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.framework.exception.BusinessException;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.th.supcom.pds.domain.pojo.PdsSupply;
import com.th.supcom.pds.domain.vo.PdsSupplyDetailVO;
import com.th.supcom.pds.domain.vo.PdsSupplyVO;
import com.th.supcom.pds.impl.common.enums.PrescSource;
import com.th.supcom.pds.impl.service.internal.chargedpresc.AbstractCommand;
import com.th.supcom.pds.impl.service.internal.chargedpresc.ChargedPrescriptionContext;

/**
 * 处方收费
 * 
 * @author wangweiquan
 */
public class PrescChargeCommand extends AbstractCommand implements Command
{

    @Override
    public boolean execute (Context context) throws Exception
    {
        ChargedPrescriptionContext con = (ChargedPrescriptionContext) context;
        Map<String,Object> map = con.getMap ();
        // 所有处方主记录
        List <PdsSupplyVO> masterList = con.getPdsSupplys ();
        List <PdsSupplyDetailVO>pdsSupplyDetailVOList=con.getPdsSupplyDetails ();
        if(map.get ("trackData")==null){
            //通过处方号查询 只有一条主记录
            if(masterList.get (0).getRcptNo ()==null){
                throw new BusinessException("该处方未收费，请到账务窗口收费");
            }else{
                return false;
            }
        }
        // 所有未收费处方处方号列表
        List <String> dbPrescNoList = new ArrayList <String> ();
        for (PdsSupply pdsSupply : masterList)
        {
            // 未收费,不是住院处方
            if (IsCharge (pdsSupply))
            {
                dbPrescNoList.add (pdsSupply.getPrescNo ());
            }
            dbPrescNoList.add (pdsSupply.getPrescNo ());
        }
        if (dbPrescNoList.isEmpty ())
        {
            return false;
        }
        if (s_logger.isInfoEnabled ())
        {
            s_logger.info ("准备执行处方收费服务，参数信息：{}", context);
        }
        List<Map<String, Object>>maps=new ArrayList<Map<String, Object>> ();
        for ( PdsSupplyDetailVO pdsSupplyDetailVO: pdsSupplyDetailVOList)
        {
            Map<String, Object>map2=new HashMap <String, Object>();
            {
                map2.put ("applyId", pdsSupplyDetailVO.getPrescNo ());
                map2.put ("itemClass", "A");//pdsSupplyDetailVO.getPhamType ()
                map2.put ("itemCode", pdsSupplyDetailVO.getPhamStdCode ());
                map2.put ("itemName", pdsSupplyDetailVO.getPhamName ());
                map2.put ("spec", pdsSupplyDetailVO.getPhamSpec ());
                map2.put ("amount", pdsSupplyDetailVO.getUnitQty ());
                map2.put ("salesPrice", pdsSupplyDetailVO.getPackagePrice ());
                map2.put ("charges", pdsSupplyDetailVO.getCosts ());
                map2.put ("externalId", pdsSupplyDetailVO.getSupplyDetailId ());
                map2.put ("costs",pdsSupplyDetailVO.getCosts () );
                map2.put ("patientId", (String)map.get ("patientId"));
                map2.put ("visitId", (Long)map.get ("visitId"));
                map2.put ("performedByDeptCode",pdsSupplyDetailVO.getPerformedBy ());
                map2.put ("orderByDeptCode",pdsSupplyDetailVO.getOrderedBy ());
                
            };
            maps.add (map2);
        }
        String rcptNo = this.getAdapterBMSChargeService ().prescriptionCharge (map, maps);
        map.put ("rcptNo", rcptNo);
        for (PdsSupply pdsSupply : masterList)
        {
            pdsSupply.setChargeDate (new Date ());
            pdsSupply.setRcptNo (rcptNo);
            //pdsSupply.setPrescStatus (ChargeIndicator.Charged.getEnumCode ());
            this.getPdsSupplyService ().modifyPdsSupplyByExample (pdsSupply);
        }
        if (s_logger.isInfoEnabled ())
        {
            s_logger.info ("处方收费执行结束");
        }
        return false;
    }

    /**
     * 
     * @param master
     * @return add by Zli
     */
    private boolean IsCharge (PdsSupply  master)
    {
        return (master.getRcptNo () == null)&& !(master.getPrescSource ()
                                                                   .equals (PrescSource.DischargeMedication.getEnumCode ())
                                                             || master.getPrescSource ()
                                                                      .equals (PrescSource.InHospital.getEnumCode ()) || master.getPrescSource ()
                                                                                                                               .equals (PrescSource.InHospitalDurgReturn.getEnumCode ()));
    }

    /** 日志记录器. */
    private static Logger s_logger = LoggerFactory.getLogger (PrescChargeCommand.class);

    /** 公司版权信息. */
    public static final String copyright = "Copyright 2014, TH Supcom Corporation";

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";

}
